﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class PlayerHealth : MonoBehaviour {
    public float hp = 100;
    public float currentHP;
    private Animator anim;
    private PlayerMove playerMove;
    private SkinnedMeshRenderer bodyRenderer;
    public float smoothing = 2f;//for player self color
    private Shoot shoot;

    public Slider healthSlider;
    public Image damageImage;
    public AudioClip deathClip;

    public float flashSpeed = 5f;//for damageImage
    public Color flashColor = new Color(1.0f, 0f, 0f, 0.15f);

    void Awake()
    {
        anim = GetComponent<Animator>();
        playerMove = GetComponent<PlayerMove>();
        bodyRenderer = transform.Find("Player").renderer as SkinnedMeshRenderer;
        shoot = GetComponentInChildren<Shoot>();
        currentHP = hp;
    }

    public void TakeDamage(float damage)
    {
        if (currentHP <= 0)
            return;
        bodyRenderer.material.color = Color.red;
        damageImage.color = flashColor;
        this.currentHP -= damage;
        audio.Play();
        if (this.currentHP <= 0)
        {
            currentHP = 0;
            Dead();
        }

        healthSlider.value = currentHP;
    }
	
	// Update is called once per frame
	void Update () {
        bodyRenderer.material.color = Color.Lerp(bodyRenderer.material.color, Color.white,
            smoothing * Time.deltaTime);
        damageImage.color = Color.Lerp(damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
	}

    void Dead()
    {
        anim.SetTrigger("Dead");
        AudioSource.PlayClipAtPoint(deathClip, transform.position);
        shoot.ShootEnd();
        playerMove.enabled = false;
        shoot.enabled = false;
    }
}
